/**
 *  File: BaoFuAPIController.java
 *  Date         Author      Changes
 *  2016-10-2    wangtq       Create
 *
 */
package com.kunpu.mami.channel.controller;



import java.util.HashMap;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.kunpu.mami.channel.common.ResConstants;
import com.kunpu.mami.channel.exception.MamiiException;
import com.kunpu.mami.channel.service.BindCardService;
import com.kunpu.mami.channel.service.SendReChargeService;
import com.kunpu.mami.channel.service.SendRePayService;
import com.kunpu.mami.channel.service.SendSmsService;

/**
 * 宝付渠道入口
 * @author wangtq
 * @date 2016-10-2 下午04:32:25
 * @version 0.1
 *
 */
@Controller
@RequestMapping("channel/baofu")
public class BaoFuAPIController {
	private final Logger       logger = LoggerFactory.getLogger(this.getClass());  
	@Autowired
	private SendSmsService sendSmsService;
	@Autowired
	private SendReChargeService sendReChargeService;
	@Autowired
	private SendRePayService sendRePayService;
	@Autowired
	private BindCardService bindCardService;
	
	public static String additionalInfo = "附加字段";
	public static String reqReserved = "请求方保留域";
	
	@Value("${trans_id_flag}") 
	private String transIdFlag;
	
	
    /**
    * 发送短信
    * @param transId   交易流水号
    * @param mobile    手机号
    * @param accNo     银行卡号
    * @param txnAmt    交易金额
    * @param bindId    银行返回bindId
    * @param nextTxnSubType  绑卡[01]/支付[04]
    * @return
    */
	@RequestMapping(value="sendSMS",method = RequestMethod.POST,produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public String sendSMS(String trans_id, String acc_no, String mobile, String bind_id, String txn_amt, String next_txn_sub_type) {
		
		//next_txn_sub_type = "04";
		Map<String,Object> sendSmsParam = this.buildSendSmsParam("TEST"+trans_id, acc_no, mobile, bind_id, txn_amt, next_txn_sub_type);
		//String logPrefix = setlogPrefix(sendSmsParam,trans_id);
		logger.info("====================渠道controller sendSMS start ===========>  ,入参为:"+sendSmsParam);
		String success = "{\"code\":\"200\",\"msg\":\"绑卡成功\"}";
		try{
			sendSmsService.sendSms(sendSmsParam);
		}catch(Exception e){
			logger.error("=====> sendSMS 发送短信时发生异常，异常信息为：",e.getMessage(),e);
			throw new MamiiException(ResConstants.INTERFACE_ACCESS_EXCEPTION.getCode() , e.getMessage());
		}
		logger.info("====================渠道controller sendSMS end ===========> ",success);
        return success;
    }
    
    /**
     * 绑卡
     * Description: 唯一订单号，8-20 位字母和数字，同一天内不可重复；
     *              如果商户开通“发送短信类交易”，该订单号从发送短信类交易到当前交易都有效
     * @param acc_no        绑定的卡号
     * @param mobile        银行卡绑定手机号
     * @param id_card       身份证号
     * @param id_holder     卡号持有人
     * @param pay_code      银行编码
     * @param sms_code     【短信验证码】
     *
     */
    @RequestMapping(value = "sendBind",method = RequestMethod.POST)
    @ResponseBody
    public String sendBind(String acc_no ,String mobile ,String id_card ,String id_holder , String pay_code , String sms_code ,String trans_id) {
        if(StringUtils.isBlank(mobile))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "手机号不能为空!");

        if(StringUtils.isNumeric(mobile) && mobile.length() != 11)
            throw new MamiiException(ResConstants.MOBLIE_FORMAT_EXCEPTION.getCode() , ResConstants.MOBLIE_FORMAT_EXCEPTION.getMsg());

        if(StringUtils.isBlank(acc_no))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "卡号不能为空!");

        if(StringUtils.isBlank(id_card))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "身份证号不能为空!");

        if(StringUtils.isBlank(id_holder))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "持卡人姓名不能为空!");

        if(StringUtils.isBlank(pay_code))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "银行编码不能为空!");

        if(StringUtils.isBlank(sms_code))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "银行编码不能为空!");
        if(StringUtils.isBlank(trans_id))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "流水号不能为空!");

        bindCardService.sendBind(acc_no, id_card, id_holder, mobile, pay_code, sms_code, trans_id);

        return "{\"code\":\"200\",\"msg\":\"绑卡成功\"}";
    }
    
    /**
     *  支付
     *  Description: 唯一订单号，8-20
     *               位字母和数字，同一天内不可重复；如果商户开通“发送短信类交易”，该订单号从发送短信类交易到当前交易都有效
     * @param sms_code 【短信验证码】
     * @param bind_id  【唯一标识符】
     * @param txn_amt  【交易金额】
     * @param accNo    【卡号】
     * @return
     */
	@RequestMapping(value="sendPay",produces={"application/json; charset=UTF-8"})
    @ResponseBody
    public String sendPay(String trans_id, String bind_id, String txn_amt, String sms_code, String additional_info, String req_reserved) {
        
		if(StringUtils.isBlank(trans_id))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "订单号不能为空!");

        if(StringUtils.isBlank(bind_id))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "唯一标识符不能为空!");

        if(StringUtils.isBlank(txn_amt))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "交易金额不能为空!");

        if(sms_code==null)
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "短信验证码不能为空!");
        
        sendReChargeService.sendReCharge(trans_id, bind_id, txn_amt, sms_code, additionalInfo, additionalInfo);
        return "{\"code\":\"200\",\"msg\":\"支付成功\"}";
    }
    
    /**
     *提现
     * @param trans_id  订单
     * @param txn_amt   提现金额
     * @param userName  用户名称
     * @param accNo     银行卡号
     * @param banckname 银行名称 
     * @return
     */
    @RequestMapping(value = "sendrePay",method = RequestMethod.POST)
    @ResponseBody
    public String rePay(String transId , String txnAmt,String userName,String accNo,String bankName ) {
        if(StringUtils.isBlank(transId))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "订单号不能为空!");

        if(StringUtils.isBlank(txnAmt))
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "交易金额不能为空!");

        if(userName == null)
            throw new MamiiException(ResConstants.PARAM_NOT_NULL.getCode() , "提现用户不能为空!");
        sendRePayService.sendRePay(transId, txnAmt, userName, accNo, bankName);
        return "{\"code\":\"200\",\"msg\":\"支付成功\"}";
    } 
    
    //组装发送短信数据入参
    private Map<String,Object> buildSendSmsParam(String trans_id, String acc_no, String mobile, String bind_id, String txn_amt, String next_txn_sub_type){
    	Map<String, Object> param = new HashMap<String, Object>();
    	param.put("trans_id", trans_id);
    	param.put("acc_no", acc_no);
    	param.put("mobile", mobile);
    	param.put("bind_id", bind_id);
    	param.put("txn_amt", txn_amt);
    	param.put("next_txn_sub_type", next_txn_sub_type);
    	return param;
    }
/*    public void sendFoPay(RePayMode payMode) throws Exception {
        TransReqBF0040001 transReqData = new TransReqBF0040001();
        transReqData.setTrans_no(payMode.getTransId());
        transReqData.setTrans_money(payMode.getTxnAmt());
        transReqData.setTo_acc_name(payMode.getIdHolder());
        transReqData.setTo_acc_no(payMode.getAccNo());
        transReqData.setTo_bank_name(payMode.getBankName());
        transReqData.setTo_pro_name("");
        transReqData.setTo_city_name("");
        transReqData.setTo_acc_dept("");
        transReqData.setTrans_summary("gs"+new Date());
        foPayService(transReqData);
    }*/

    /*private SendSmsDto convertSendSms(String transId, String accNo, String mobile, String bindId, String txnAmt, String nextTxnSubType, String additionalInfo, String reqReserved){
    	SendSmsDto sendSmsDto = new SendSmsDto();
    	sendSmsDto.setTransId(transId);
    	sendSmsDto.
    	
    	return sendSmsDto;
    }*/
  
 
	
	//日志上下文
/*//	public static String setlogPrefix (Map map,String transId){
//	    String logPrefix = String.format(" baofu-channel:-%s-%s", map.hashCode(),transId );
//	    return logPrefix;
//	}
*/	

	
	public String getTransIdFlag() {
		return transIdFlag;
	}
	public void setTransIdFlag(String transIdFlag) {
		this.transIdFlag = transIdFlag;
	}	
    
}
